package com.ttmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ttmall.product.service.CategoryBrandRelationService;
import com.ttmall.product.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ttmall.common.utils.PageUtils;
import com.ttmall.common.utils.Query;

import com.ttmall.product.dao.CategoryDao;
import com.ttmall.product.entity.CategoryEntity;
import com.ttmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        //1. 查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> menus = categoryEntities.stream()
                .filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == 0;
                })
                .map(menu -> {
                    menu.setChildren(getChildren(menu, categoryEntities));
                    return menu;
                })
                //.sorted((menu1, menu2) -> {
                //    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                //})
                .collect(Collectors.toList());


        return menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional
    @Override
    //@CacheEvict(value={"category"} , key = "getLevel1Categories")
    //@Caching(
    //        evict = {
    //                @CacheEvict(value={"category"} , key = "getLevel1Categories"),
    //                @CacheEvict(value={"category"} , key = "getCatalogJson")
    //        }
    //)
    @CacheEvict(value = "category" , allEntries = true)
    //@CachePut  双写模式
    public void  updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    //每一个需要缓存的数据都要指定放到那个名字的缓存【缓存的分区】
    @Cacheable(value= {"category"},key="#root.method.name") // 代表当前方法的结果需要缓存，如果缓存中有，方法不用调用。如果缓存中没有，则会调用方法，最后将方法的返回值进行缓存
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("getLevel1Categories...");
        List<CategoryEntity> list = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }

    @Cacheable(value = "category" , key="#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1Categories = getParentCid(selectList, 0l);//getLevel1Categories();

        Map<String, List<Catelog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {

                    List<CategoryEntity> categories = getParentCid(selectList, v.getCatId());
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categories != null) {
                        catelog2Vos = categories.stream()
                                .map(e -> {
                                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, e.getCatId().toString(), e.getName());
                                    List<CategoryEntity> catelog3List = getParentCid(selectList, e.getCatId());

                                    if (catelog3List != null) {

                                        List<Catelog2Vo.Catelog3Vo> collect = catelog3List.stream().map(l3 -> {
                                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(e.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                                            return catelog3Vo;
                                        }).collect(Collectors.toList());

                                        catelog2Vo.setCatalog3List(collect);
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                    }

                    return catelog2Vos;
                }
        ));
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonRedis() {

        /**
         * 1. 空结果缓存： 解决缓存穿透
         * 2. 设置过期时间（加随机值）： 解决缓存雪崩
         * 3. 加锁： 解决缓存击穿
         */
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");

        if (StringUtils.isEmpty(catalogJson)) {
            System.out.println("---查询数据库--- ");
            Map<String, List<Catelog2Vo>> catalogJsonFromdb = getCatalogJsonFromdbWithRedisLock();
            return catalogJsonFromdb;
        }
        System.out.println("---读取缓存--- ");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });

        return result;

    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromdbWithRedissonLock() {
        // 分布式锁：
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();

        System.out.println("加锁成功。。。");
        Map<String, List<Catelog2Vo>> data;
        try {
            data = getCategoriesJsonMap();
        } finally {
            lock.unlock();
        }
        return data;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromdbWithRedisLock() {
        // 分布式锁：
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("加锁成功。。。");
            Map<String, List<Catelog2Vo>> data;
            try {
                //redisTemplate.expire("lock" , 30, TimeUnit.SECONDS);
                data = getCategoriesJsonMap();
            } finally {
                // 获取值对比+ 对比成功删除= 原子操作    lua脚本
                //String lockVal = redisTemplate.opsForValue().get("lock");
                //if (uuid.equals(lockVal)){
                //    redisTemplate.delete("lock");
                //}
                //http://www.redis.cn/commands/set.html
                String scripts = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";

                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(scripts, Long.class), Arrays.asList("lock"), uuid);

            }
            return data;
        } else {
            // 加索失败。。重试
            System.out.println("加锁失败。。。等待重试");

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromdbWithRedisLock(); // 自旋的方式
        }

    }

    private Map<String, List<Catelog2Vo>> getCategoriesJsonMap() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");

        if (!StringUtils.isEmpty(catalogJson)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });

            return result;
        }
        System.out.println("---查询数据库--- 1");
        List<CategoryEntity> selectList = baseMapper.selectList(null);


        List<CategoryEntity> level1Categories = getParentCid(selectList, 0l);//getLevel1Categories();

        Map<String, List<Catelog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {

                    List<CategoryEntity> categories = getParentCid(selectList, v.getCatId());
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categories != null) {
                        catelog2Vos = categories.stream()
                                .map(e -> {
                                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, e.getCatId().toString(), e.getName());
                                    List<CategoryEntity> catelog3List = getParentCid(selectList, e.getCatId());

                                    if (catelog3List != null) {

                                        List<Catelog2Vo.Catelog3Vo> collect = catelog3List.stream().map(l3 -> {
                                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(e.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                                            return catelog3Vo;
                                        }).collect(Collectors.toList());

                                        catelog2Vo.setCatalog3List(collect);
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                    }

                    return catelog2Vos;
                }
        ));

        String jsonString = JSON.toJSONString(parent_cid);

        redisTemplate.opsForValue().set("catalogJson", jsonString, 1, TimeUnit.DAYS);

        return parent_cid;
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromdbWithLocalLock() {

        synchronized (this) {
            return getCategoriesJsonMap();
        }
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        List<CategoryEntity> collect = selectList.stream().filter(e -> e.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildren(CategoryEntity categoryEntity, List<CategoryEntity> all) {

        List<CategoryEntity> childred = all.stream().filter(categoryEntity1 -> {
            return categoryEntity1.getParentCid() == categoryEntity.getCatId();
        }).map(categoryEntity1 -> {
            categoryEntity1.setChildren(getChildren(categoryEntity1, all));
            return categoryEntity1;
        }).sorted((menu1, menu2) -> {
            if (menu1 == null) return -1;
            if (menu2 == null) return 1;
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return childred;
    }

}